package com.example.music;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.lwx.R;

public class PlayActivity extends Activity implements View.OnClickListener {
    Button bt_bind, bt_stop, bt_play, bt_unbind;
    MusicService.MyBinder myBinder;
    ServiceConnection conn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_main);
        bt_bind = findViewById(R.id.btn_bind);
        bt_stop = findViewById(R.id.btn_stop);
        bt_play = findViewById(R.id.btn_play);
        bt_unbind = findViewById(R.id.btn_unbind);
        bt_bind.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        bt_unbind.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_bind) {
            if (conn == null) {
                conn = new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                        myBinder = (MusicService.MyBinder) iBinder;
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName componentName) {

                    }
                };

            }
            Intent intent = new Intent(PlayActivity.this, MusicService.class);
            bindService(intent, conn, BIND_AUTO_CREATE);
            Toast.makeText(PlayActivity.this, "播放服务绑定成功", Toast.LENGTH_SHORT).show();
       }
      if(view.getId()==R.id.btn_play) {
          myBinder.play();
      }
   if(view.getId()==R.id.btn_stop){
       myBinder.stop();
   }
   if(view.getId()==R.id.btn_unbind){
       unbindService(conn);
       Toast.makeText(PlayActivity.this, "播放服务解绑成功", Toast.LENGTH_SHORT).show();
   }
    }
}